<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<style>

  #div1 .active {
    background-color: yellow;
  }
</style>

<body>
  <div id="div1">
    <input class="active" type="button" value="选项卡1" />
    <input type="button" value="选项卡2" />
    <input type="button" value="选项卡3" />
    <input type="button" value="选项卡4" />
    <div>选项卡1</div>
    <div style="display: none;">选项卡2</div>
    <div style="display: none;">选项卡3</div>
    <div style="display: none;">选项卡4</div>
  </div>

  <script>
    let div1 = document.getElementById("div1")
    let buttons = div1.getElementsByTagName("input")
    let subDiv = div1.getElementsByTagName("div")

    for (let i = 0; i < buttons.length; i++) {
      //设置一个自定义“index”属性
      buttons[i].index = i
      buttons[i].onclick = function () {
        //遍历
        for (let i = 0; i < buttons.length; i++) {
          buttons[i].className = ""
          subDiv[i].style.display = "none"
        }
        this.className = "active"
        subDiv[this.index].style.display = "block"

      }

    }


  </script>
</body>

</html>